import os
import re
class file_conversion:
    def extraction_dialog(self, path):
        file_path = path;
        lines = []  # 待写入的文本

        # 打开文件进行读取
        with open(file_path, 'r', encoding='utf-8') as file:
            count = 1
            line = file.readline()  # 读取第一行
            while line:
                text = line
                if len(text) > 2:
                    match = re.search(r'": "(.*)"', text)
                    if match: # 判断内容是否正确
                        text = match.group(1)
                        # 排除干扰项
                        if re.match(
                                r'^[a-zA-ZÀ-ÿÁ-ý0-9\s\\\_\|\…\.\,\:\~\【\】\·\「\」\—\/\{\}\(\)\[\]\'\"\?\!\;\^\*\ﾟ\｡\=\-\✰\`\r\%\+\&\─\。]+$',
                                text) is None:
                            lines.append(str(count) + " : \" " + text + " \",");
                count = count + 1
                line = file.readline()  # 读取下一行

        # 获取文件路径和文件名
        path, filename = os.path.split(file_path)
        filename = "new_" + filename
        # 构建新文件路径
        file_path = os.path.join(path, filename)
        # 打开文件进行写入，使用UTF-8编码
        with open(file_path, 'w', encoding='utf-8') as file:
            for line in lines:
                file.write(line + '\n')  # 写入每一行并添加换行符

    def split(self, path):
        file_path = path
        lines = []  # 待写入的文本

        # 打开文件进行读取
        with open(file_path, 'r', encoding='utf-8') as file:
            line = file.readline()  # 读取第一行
            while line:
                text = line
                num = 0
                if len(text) > 2:
                    # 导出数字
                    match = re.match(r'^[\d]+', text)
                    if match:
                        num = match.group()
                        match = re.search(r' : " (.*) ",', text)
                        if match:
                            text = match.group(1)
                            # 转换成可以翻译的格式,strip()去除行末尾的换行符
                            text = text.strip() \
                                .replace('\\n', '\n') \
                                .replace('\\r', '\r') \
                                .replace('\\"', '\"') \
                                .replace("\\'", "\'") \
                                .replace('\\t', '\t') \
                                .replace('\\\\', '\\')
                            lines.append([num, text]);
                line = file.readline()  # 读取下一行

        # 获取文件路径和文件名
        path, filename = os.path.split(file_path)
        name, extension = os.path.splitext(filename)
        # 构建新文件路径
        file_path = os.path.join(path, name)
        # 创建文件夹
        os.makedirs(file_path)
        # 打开文件进行写入，使用UTF-8编码
        for line in lines:
            with open(os.path.join(file_path, line[0]) + ".txt", 'w', encoding='utf-8') as file:
                file.write(line[1])

    def replacement(self, dirpath, filepath):
        dir_path = dirpath
        file_path = filepath
        origi_lines = [""]  # 待写入的文本
        trans_lines = []  # 翻译文本
        # 打开文件进行读取

        # 读取待翻译文件
        with open(file_path, 'r', encoding='utf-8') as file:
            line = file.readline()  # 读取第一行
            while line:
                origi_lines.append(line)
                line = file.readline()  # 读取下一行

        # 遍历文件夹中的所有文件
        text_files = []
        for filename in os.listdir(dir_path):
            path = os.path.join(dir_path, filename)
            # 判断文件是否为普通文件并且文件名以 .txt 结尾
            if os.path.isfile(path) and filename.endswith('.txt'):
                text_files.append(path)
        for text_file in text_files:
            with open(text_file, 'r', encoding='utf-8') as file:
                file_contents = file.read().strip()
                path, filename = os.path.split(text_file)
                name, extension = os.path.splitext(filename)
                # 组装回原格式
                file_contents = repr(file_contents)[1:-1].replace('\"', '\\"').replace("\'", "\\'")
                trans_lines.append([int(name), file_contents])
        # 覆盖原文
        for trans_line in trans_lines:
            text = origi_lines[trans_line[0]]
            if len(text) > 2:
                match = re.search(r'": "(.*)"', text)
                if match:
                    origi_lines[trans_line[0]] = origi_lines[trans_line[0]][:match.start() + 4] \
                                                 + trans_line[1] \
                                                 + origi_lines[trans_line[0]][match.end() - 1:]

        # 获取文件路径和文件名
        path, filename = os.path.split(file_path)
        # 构建新文件路径
        file_path = os.path.join(path, "TranslationCompleted.json")

        # 打开文件进行写入，使用UTF-8编码
        with open(file_path, 'w', encoding='utf-8') as file:
            for line in origi_lines[1:]:
                file.write(line)  # 写入每一行并添加换行符

if __name__ == '__main__':
    pass